import sqlalchemy as sa

from sqlalchemy import create_engine,Table, Column
from sqlalchemy import orm
from sqlalchemy.orm import relation as relationship,backref,sessionmaker

import time

from mudpyl import colors

DEBUG=True

engine = create_engine('sqlite:///:memory:', echo=DEBUG)
Session=sessionmaker(bind=engine)

meta=sa.MetaData()

color_table=Table('color',meta,
        Column('id',sa.types.Integer,primary_key=True),
        Column('fore',sa.types.String(30)),
        Column('back',sa.types.String(30)),
        Column('bold',sa.types.Boolean),
        )

string_table=Table('string',meta,
        Column('id',sa.types.Integer,primary_key=True),
        Column('time',sa.types.Float),
        Column('content',sa.types.String(300)),
        Column('color_id',sa.ForeignKey('color.id'))
        )

class String(object):

    def __init__(self,content,color):

        self.color=color

        self.time=time.time()
        self.content=content

    def colored(self,needBack=False):

        from mudpyl.ui.cli_color import colored

        return colored(color=(colors.fg_code(self.color.fore,self.color.bold),
            colors.bg_code(self.color.back)),
                text=self.content,needBack=needBack)

    def __repr__(self):

        return '%s (%s%s @%s)' % (self.content,self.color,
                ' , bold' if self.bold else '',
                time.strf('%H:%M:%S',time.localtime(self.time)))

class Color(object):

    def __init__(self,fore,back,bold=False):
        self.fore=fore
        self.back=back
        self.bold=bold

    def __repr__(self):
        return ' (%s , %s) ' % (self.fore,self.back)

orm.mapper(String,string_table,
        properties={
            'color':relationship(Color,backref='strings',uselist=False)
        })

orm.mapper(Color,color_table)

def init():

    meta.create_all(engine)
